//
//  DYWComposeController.swift
//  sinaWeibo
//
//  Created by 董艳武 on 16/2/25.
//  Copyright © 2016年 董艳武. All rights reserved.
//

import UIKit
import SnapKit
import AFNetworking
import SVProgressHUD
class DYWComposeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置控制器的背景颜色
        view.backgroundColor = UIColor.whiteColor()
        setNav()
        setTextView()
        setToolBar()
        // 注册通知
        registerSystemNoti()
        setPicSelector()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
   
    
    // MARK:--懒加载 textView
    private lazy var textView:UITextView = UITextView()
    
    // MARK:--懒加载 toolBar 
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    // MARK:--懒加载文字label 用来遮盖 textView 上的初始的文字
    private lazy var placeHolder:UILabel = UILabel(fontSize: 16, alignment: NSTextAlignment.Left, contentColor: UIColor.darkGrayColor(), isSizeToFit: true, lineCount: 1, labelText: "写下你的微博....")
    
    // MARK:--图片选择器的控制器
    private lazy var picSelector:DYWPickerSelector = DYWPickerSelector()
    
    // MARK:--懒加载约束属性
    private var picHeightConstraint:Constraint?
    
    // MARK:--图片选择器是否是显示的
    private var isShowPicSelector = false
    
    // MARK:--添加键盘的系统通知
    private func registerSystemNoti () {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didiClickToChangeKeyboardHeight:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        /*
        UIKeyboardWillChangeFrameNotification 将要改变 frame 的通知
        UIKeyboardDidChangeFrameNotification  已经改变 frame 的通知
        */
    }
    
    // MARK:--移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK:--通知的监听事件
    @objc private func didiClickToChangeKeyboardHeight(n:NSNotification) {
        
        // 获取变化的键盘的 frame
        let changedFrame = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        // 获取动画的时间持续时间
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        // 获取动画曲线值
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
//        print(changedFrame,duration,curve)
        // 获取 toolBar 要变化的值
        let changedHeight = -(screenHeight - changedFrame.origin.y)

        UIView.animateWithDuration(duration) { () -> Void in
            // 在动画闭包中设置曲线
            // 通过原始值 获取枚举类型的对象 7 表示忽略时间
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            // 更新约束
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(changedHeight)
            })
            // 强制刷新页面
            self.view.layoutIfNeeded()
        }
        
    }
}


// MARK: -- 设置 UI 的分类 实现点击事件
// MARK: -- 设置导航栏控制器
extension DYWComposeController {
    /// 设置导航栏控制器的样式
    private func setNav () {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "didClickToGoBacK")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "didClickToRelease")
        
        // 发布按钮默认是不能点击的
        self.navigationItem.rightBarButtonItem?.enabled = false
        
//        self.title = "创建微博"
        
        // MARK:--懒加载 titleView 上的 label
        let composeLabel = UILabel(fontSize: 18, alignment: .Center, contentColor: UIColor.blackColor(), isSizeToFit: true, lineCount: 1, labelText: "创建微博")
        let nameLabel = UILabel(fontSize: 16, alignment: .Center, contentColor: UIColor.darkGrayColor(), isSizeToFit: true, lineCount: 1, labelText: DYWOauthViewModel.sharedInstance.userName)
        
        // MARK:-- 自定义导航栏控制器的 titleView
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        // 默认的导航栏控制器的 titleView 为 nil
        self.navigationItem.titleView = titleView
        
        // 添加 label
        titleView.addSubview(composeLabel)
        titleView.addSubview(nameLabel)
        composeLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
    }
    
    /// 点击返回的监听事件
    @objc private func didClickToGoBacK () {
        print(__FUNCTION__)
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 点击发布的监听事件
    @objc private func didClickToRelease () {
        print(__FUNCTION__)
//        sendWeibo()
        sendWeiWithPicture()

    }
}

// MARK: -- 设置 textView
extension DYWComposeController:UITextViewDelegate{
    
    private func setTextView () {
        self.view.addSubview(textView)
        textView.backgroundColor = HotPink
//        textView.text = "写下你的微博...."
        textView.textColor = UIColor.darkGrayColor()
        textView.font = UIFont.systemFontOfSize(16)
        textView.delegate = self
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.view.snp_top)
            make.left.right.equalTo(self.view)
            make.height.equalTo(self.view.bounds.height / 3)
        }
        textView.addSubview(placeHolder)
        placeHolder.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    //  UITextView 的代理方法 textView 发生改变时会调用这个方法
    func textViewDidChange(textView: UITextView) {
        placeHolder.hidden = textView.hasText()
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

// MARK: -- 设置 toolBar
extension DYWComposeController {
    
    private func setToolBar () {
        self.view.addSubview(toolBar)
        
        let itemArr = [["imgName":"compose_toolbar_picture",
                         "actionName":"didClickToAddImgs"],[
                         "imgName":"compose_mentionbutton_background"],[
                         "imgName":"compose_emoticonbutton_background",
                         "actionName":"didClickToAddEmotion"],[
                         "imgName":"compose_keyboardbutton_background"],[
                         "imgName":"compose_add_background"]]
        var items = [UIBarButtonItem]()
        
        
        for item in itemArr {
            if let name = item["imgName"] {
                let btn = UIButton(img: nil, bgImg: name)
                let barBtn = UIBarButtonItem(customView: btn)
                if let target = item["actionName"] {
                    let selector = Selector(target)
                    btn.addTarget(self, action: selector, forControlEvents: .TouchUpInside)
                }
                items.append(barBtn)
                let flxBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
                items.append(flxBtn)
            }
        }
//        print(items.count)
        items.removeLast()
        toolBar.items = items
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self.view)
//            make.height.equalTo(44)
        }
    }
    
    //MARK:-- 为 toolBar 的按钮添加点击事件
    /// 添加图片按钮的点击事件
    @objc private func didClickToAddImgs () {
        print(__FUNCTION__)
        if isShowPicSelector == false {
            self.textView.resignFirstResponder()
            self.picSelector.view.snp_updateConstraints { (make) -> Void in
                make.top.equalTo(self.view.snp_bottom).offset(-screenHeight / 3 * 2)
            }
        } else {
            self.picSelector.view.snp_updateConstraints { (make) -> Void in
                make.top.equalTo(self.view.snp_bottom).offset(screenHeight / 3 * 2)
            }
        }
        self.view.bringSubviewToFront(toolBar)
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
        isShowPicSelector = !isShowPicSelector

    }
    
    /// 添加表情的点击事件
    @objc private func didClickToAddEmotion () {
        print(__FUNCTION__)
    }
}

// MARK:--设置图片选择器
extension DYWComposeController {
    private func setPicSelector () {
        // 添加视图控制器 会出现视图数的问题
        self.addChildViewController(picSelector)
        // 添加 view
        self.view.addSubview(picSelector.view)
        // 添加约束
        picSelector.view.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.view.snp_bottom)
            make.right.left.equalTo(self.view)
            make.height.equalTo(screenHeight / 3 * 2)
        }
        
    }
}

// MARK:--发送微博的方法
extension DYWComposeController {
    private func sendWeibo () {
        /*
        
        必选	类型及范围	说明
        access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
        status	true	string	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
        visible	false	int	微博的可见性，0：所有人能看，1：仅自己可见，2：密友可见，3：指定分组可见，默认为0。
        list_id	false	string	微博的保护投递指定分组ID，只有当visible参数为3时生效且必选。
        lat	false	float	纬度，有效范围：-90.0到+90.0，+表示北纬，默认为0.0。
        long	false	float	经度，有效范围：-180.0到+180.0，+表示东经，默认为0.0。
        annotations	false	string	元数据，主要是为了方便第三方应用记录一些适合于自己使用的信息，每条微博可以包含一个或者多个元数据，必须以json字串的形式提交，字串长度不超过512个字符，具体内容可以自定。
        rip	false	string	开发者上报的操作用户真实IP，形如：211.156.0.1
        */
        let afn = AFHTTPSessionManager()
        
        var params = [String:AnyObject]()
        
        params["access_token"] = DYWOauthViewModel.sharedInstance.access_token
        params["status"] = textView.text
        
        afn.POST("https://api.weibo.com/2/statuses/update.json", parameters: params, progress: nil, success: { (_, success) -> Void in
            
            print(success)
            SVProgressHUD.showInfoWithStatus("发送成功，正在跳转。。。")
            self.dismissViewControllerAnimated(true, completion: nil)
            
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败，请检查网络")
        }
    }
    private func sendWeiWithPicture () {
        
        guard let _ = DYWOauthViewModel.sharedInstance.access_token else {
            SVProgressHUD.showErrorWithStatus("请登陆！")
            return
        }
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        let afn = AFHTTPSessionManager()
        var params = [String:AnyObject]()
        params["access_token"] = DYWOauthViewModel.sharedInstance.access_token
        params["status"] = textView.text
        if self.picSelector.images.count > 0 {
            urlString =  "https://upload.api.weibo.com/2/statuses/upload.json"
            
            afn.POST(urlString, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
                /*
                data: NSData     需要上传的文件的二进制数据
                name: String     服务器的接收字段名
                fileName: String 服务器存储的文件的名称 微博服务器会重新命名
                mimeType: String 文件格式
                */
                var index = 0
                for image in self.picSelector.images {
                    let imageData = UIImagePNGRepresentation(image)!
                    formData.appendPartWithFileData(imageData, name: "pic", fileName: "fileName\(index)", mimeType: "image/jpeg")
                    index++
                }
                
//                formData.appendPartWithFileData(imageData, name: "pic", fileName: "oooxxx", mimeType: "image/jpeg")
                }, progress: nil, success: { (_, success) -> Void in
                    print(success)
                    SVProgressHUD.showInfoWithStatus("发送成功正在跳转")
                    self.dismissViewControllerAnimated(true, completion: nil)
                }) { (_, error) -> Void in
                    print(error)
                    SVProgressHUD.showErrorWithStatus("发送失败，请检查网络")
            }
        }
        
    }
}